app.controller('DemandOneCtrl', ['$scope', '$timeout', '$http', '$compile', 'toaster', '$location', '$modal', 'R', 'FileUploader', '$q', '$rootScope',
function($scope, $timeout, $http, $compile, toaster, $location, $modal, R, FileUploader, $q, $rootScope) {
    
    function initEditor(content){
        var editor = UE.getEditor('myEditor'+$scope.editorid,{
            toolbars:[['fullscreen', 'source', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'strikethrough', 'removeformat', 'formatmatch', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
            'link', 'unlink', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
            'simpleupload', 'pagebreak', 'background', 'insertvideo', '|',
            'horizontal', 'date', 'time', 'snapscreen', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
            'print', 'preview', 'searchreplace', 'drafts', 'help']],
            autoClearinitialContent:true,
            autoHeightEnabled: false,
            wordCount:false,
            elementPathEnabled:false,
            initialFrameHeight:800,
            serverUrl: R.getFileUpload(),
            imageActionName: 'uploadImage',
            imageFieldName: 'inputFile',
            imageFieldTypeValue: 1
        });

        editor.ready(function(){
            UE.getEditor('myEditor'+$scope.editorid).setContent(content);
        });
    }
    
    $scope.editorid = Math.floor(Math.random()*10000);

    R.getAddressList().then(function(data){
        $scope.mappers.address = data.bizData;

        var urlparams = $location.search();
        $scope.id = urlparams.id;

        if ($scope.id) {
            R.getDemandDetailById({id: $scope.id}).then(function(data){
                $scope.item = data.bizData;

                $scope.model.priceRange = $scope.item.priceRange.split('-');
                $scope.model.jobRange = $scope.item.jobRange.split('-');
                $scope.model.tags = $scope.item.tags;

                setTimeout(function(){
                    initEditor($scope.item.comment);
                }, 1000);

                var a = $scope.item.address.split('-');
                if (a[0]){
                    angular.forEach($scope.mappers.address, function(item){
                        if (item.name == a[0]){
                            $scope.model.l1 = item;
                        
                            if (a[1]){
                                angular.forEach(item.childs, function(item){
                                    if (item.name == a[1]){
                                        $scope.model.l2 = item;
                                        
                                        if (a[2]){
                                            angular.forEach(item.childs, function(item){
                                                if (item.name == a[2]){
                                                    $scope.model.l3 = item;
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        }
                    });
                }

                
            });
        }else{
            $scope.item = {
                isTrue: 0,
                checkState: 0,
                classifyId: 0,
                comment: '',
                companyName: '',
                demandName: '',
                isDisplay: 0,
                order: 0,
                phone: '',
                recruitState: 0
            }

            setTimeout(function(){
                initEditor('');
            }, 1000);
        }
    });

    $scope.$watch('model.l1', function(newval){
        if (newval && $scope.model.l2 && $scope.model.l2.parentId != newval.id){
            $scope.model.l2 = null;
        }
    });

    $scope.$watch('model.l2', function(newval){
        if (newval && $scope.model.l3 && $scope.model.l3.parentId != newval.id){
            $scope.model.l3 = null;
        }
    });

    R.getRecomandIndex({type: 1}).then(function(data){
        $scope.mappers.order = [0].concat(data.bizData);
    });

    $scope.mappers = {
        classifyId: [],
        directionId: [],
        order: [],
        checkState: [{
            'id': 0,
            'name': '未审核'
        },{
            'id': 1,
            'name': '已审核'
        }],
        authState:  [{
            'id': 0,
            'name': '未认证'
        },{
            'id': 1,
            'name': '已认证'
        }],
        recruitState: [{
            'id': 0,
            'name': '未招募'
        },{
            'id': 1,
            'name': '已招募'
        }],
        contactState: [{
            'id': 0,
            'name': '未联系'
        },{
            'id': 1,
            'name': '已联系'
        }],
        isDisplay: [{
            'id': 0,
            'name': '否'
        },{
            'id': 1,
            'name': '是'
        }],
        recommandTags: []
    }

    $scope.model = {
        l1: null,
        l2: null,
        l3: null,
        priceRange: [0],
        jobRange: [],
        tags: []
    }

    R.getAllClassifyAndDirection().then(function(data){
        $scope.mappers.classifyId = data.bizData.classifys;
        $scope.mappers.directionId = data.bizData.directions;
    });

    $scope.uploader = new FileUploader({
        url: R.getFileUpload(),
        formData: [{
            type: 1
        }],
        autoUpload: true,
        alias: 'inputFile'
    });

    $scope.uploader.onCompleteItem = function(res, data){
        $scope.item.coverPic = data.bizData.attachmentUrl;
        $scope.item.attachmentUrl = data.bizData.attachmentUrl;
        $scope.item.attachmentName = data.bizData.attachmentName;
        $scope.item.attachmentSize = data.bizData.attachmentSize;
    };

    R.getRecomandTags({type: 0}).then(function(data){
        $scope.mappers.recommandTags = data.bizData;
    });

    $scope.addTag = function(tag){
        var deferred = $q.defer();

        R.saveTag({
            "tagName": tag.name,
            "type": 0
        }).then(function(data){
            deferred.resolve({id: data.bizData.id, name: tag.name});
        });

        return deferred.promise;
    }

    $scope.addTags = function(tag){
        var flag = false;
        angular.forEach($scope.model.tags, function(i){
            if (i.id == tag.id){
                flag = true;
            }
        });
        if (flag) return;

        $scope.model.tags.push({
            id: tag.id,
            name: tag.tagName
        });
    }

    $scope.opened = [];
    $scope.open = function($event,index) {
        $event.preventDefault();
        $event.stopPropagation();
        $scope.opened[index] = true;
    };

    $scope.submit = function(){
        var adds = [];
        if ($scope.model.l1) {
            adds.push($scope.model.l1.name);
        }
        if ($scope.model.l2) {
            adds.push($scope.model.l2.name);
        }
        if ($scope.model.l3) {
            adds.push($scope.model.l3.name);
        }

        $scope.item.address = adds.join('-');

        $scope.item.publishTime = R.getTimeFormat($scope.item.publishTime || new Date(), 'yyyy-MM-dd');
        
        if (!$scope.model.priceRange[0]){
            $scope.model.priceRange[0] = 0;
        }
        $scope.item.priceRange = $scope.model.priceRange.join('-');
        $scope.item.jobRange = $scope.model.jobRange.join('-');

        $scope.item.tagIds = [];

        $scope.item.comment = UE.getEditor('myEditor'+$scope.editorid).getContent();

        angular.forEach($scope.model.tags, function(item){
            $scope.item.tagIds.push(item.id);
        });
        $scope.item.tagIds = $scope.item.tagIds.join(',');

        if ($scope.item.id){
            R.updateDemand($scope.item).then(function(data){
                toaster.success("操作成功");
                $location.url("/app/demand/list");
            });
        }else{
            var user = $rootScope.getSgObj('LOGINUSER');
            $scope.item.userId = user.id;
            R.addDemand($scope.item).then(function(data){
                toaster.success("操作成功");
                $location.url("/app/demand/list");
            });
        }
    }

}]);